<template>
  <div class="w-full px-4 py-3 flex items-center gap-4 text-white task-panel">
    <span class="text-sm">任务计划库</span>

    <div class="flex items-center gap-4 flex-1">
      <div class="flex items-center gap-2">
        <span class="text-sm text-gray-400">状态:</span>
        <el-select
          v-model="searchParams.status"
          placeholder="请选择状态"
          class="width-common"
          @change="handleSearchParamsStatusChange"
        >
          <el-option v-for="item in TaskStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>

      <div class="flex items-center gap-2">
        <span class="text-sm text-gray-400">计划名称:</span>
        <el-input
          v-model="searchParams.jobName"
          class="width-common"
          placeholder="请输入计划名称"
          @keypress.enter="getPlans({ job_name: searchParams.jobName })"
        />
        <!-- <input
          type="text"
          placeholder="请输入"
          class="bg-slate-800 border border-slate-700 rounded px-2 py-1 text-sm min-w-[150px] focus:outline-none focus:border-blue-500"
        /> -->
      </div>

      <div class="flex items-center gap-2">
        <span class="text-sm text-gray-400">类型:</span>
        <el-select
          v-model="searchParams.taskType"
          placeholder="请选择类型"
          class="width-common"
          @change="handleSearchParamsTaskTypeChange"
        >
          <el-option v-for="item in TaskTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>
  </div>
  <div class="plan-panel-wrapper">
    <el-table :data="plansData.data.concat()" border style="width: 100%" height="650">
      <el-table-column prop="duration" label="计划/实际时间">
        <template #default="scope">
          <div class="flex-row" style="white-space: pre-wrap">
            <div>
              <div>{{ formatTaskTime(scope.row.begin_time) }}</div>
              <div>{{ formatTaskTime(scope.row.end_time) }}</div>
            </div>
            <div class="ml10">
              <div>{{ formatTaskTime(scope.row.execute_time) }}</div>
              <div>{{ formatTaskTime(scope.row.completed_time) }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="job_name" label="计划名称" width="180" />

      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <div>
            <div class="flex-display flex-align-center">
              <span class="circle-icon" :style="{ backgroundColor: formatTaskStatus(scope.row).color }"></span>
              {{ formatTaskStatus(scope.row).text }}
              <a-tooltip v-if="!!scope.row.code" placement="bottom" arrow-point-at-center>
                <template #title>
                  <div>{{ getCodeMessage(scope.row.code) }}</div>
                </template>
                <exclamation-circle-outlined class="ml5" :style="{ color: commonColor.WARN, fontSize: '16px' }" />
              </a-tooltip>
            </div>
            <div v-if="scope.row.status === TaskStatus.Carrying">
              <a-progress :percent="scope.row.progress || 0" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="taskType" label="类型" width="70">
        <template #default="scope">
          <div>{{ formatTaskType(scope.row) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="file_name" label="航线名称" width="100" />
      <el-table-column prop="dock_name" label="机场名称" width="100" />
      <el-table-column prop="rth_altitude" label="RTH相对于机场的高度（m）" width="120" />
      <el-table-column prop="out_of_control_action" label="航线飞行中失联" width="120">
        <template #default="scope">
          <div>{{ formatLostAction(scope.row) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="创建者" width="100" />
      <el-table-column prop="media_upload" label="媒体文件上传" width="160">
        <template #default="scope">
          <div>
            <div class="flex-display flex-align-center">
              <span class="circle-icon" :style="{ backgroundColor: formatMediaTaskStatus(scope.row).color }"></span>
              {{ formatMediaTaskStatus(scope.row).text }} {{ formatMediaTaskStatus(scope.row).number }}
            </div>
            <div class="pl15">
              <!-- {{ formatMediaTaskStatus(scope.row).number }} -->
              <a-tooltip
                v-if="formatMediaTaskStatus(scope.row).status === MediaStatus.ToUpload"
                placement="bottom"
                arrow-point-at-center
              >
                <template #title>
                  <div>现在上传</div>
                </template>
                <UploadOutlined
                  class="ml5"
                  :style="{ color: commonColor.BLUE, fontSize: '16px' }"
                  @click="onUploadMediaFileNow(scope.row.job_id)"
                />
              </a-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template #default="{ row }">
          <div class="action-area">
            <a-popconfirm v-if="row.status === TaskStatus.Wait" title="确定要删除吗？" @confirm="onDeleteTask(row.job_id)">
              <a-button type="primary" size="small">删除</a-button>
            </a-popconfirm>
            <a-popconfirm v-if="row.status === TaskStatus.Carrying" title="您确定要暂停吗？" @confirm="onSuspendTask(row.job_id)">
              <a-button type="primary" size="small">挂起</a-button>
            </a-popconfirm>
            <a-popconfirm v-if="row.status === TaskStatus.Paused" title="您确定要继续吗？" @confirm="onResumeTask(row.job_id)">
              <a-button type="primary" size="small">继续</a-button>
            </a-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-end mt-6">
      <el-pagination
        v-model:current-page="paginationProp.current"
        v-model:page-size="paginationProp.pageSize"
        :page-sizes="paginationProp.pageSizeOptions"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="总数, sizes, prev, pager, next, jumper"
        :total="paginationProp.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ExclamationCircleOutlined, UploadOutlined } from '@ant-design/icons-vue'
import { reactive, ref } from '@vue/reactivity'
import { message } from 'ant-design-vue'
import { TableState } from 'ant-design-vue/lib/table/interface'
import { ComponentSize } from 'element-plus'
import { onMounted } from 'vue'
import { useFormatTask } from './use-format-task'
import { useTaskWsEvent } from './use-task-ws-event'
import { IPage } from '@/api/http/type'
import { deleteTask, getWaylineJobs, Task, updateTaskStatus, UpdateTaskStatus, uploadMediaFileNow } from '@/api/wayline'
import { useMyStore } from '@/store'
import { ELocalStorageKey } from '@/types/enums'
import {
  TaskStatusOptions,
  MediaStatus,
  MediaStatusProgressInfo,
  TaskMediaHighestPriorityProgressInfo,
  TaskProgressInfo,
  TaskProgressStatus,
  TaskProgressWsStatusMap,
  TaskStatus,
  TaskTypeOptions,
  TaskType
} from '@/types/task'
import { commonColor } from '@/utils/color'
import { getErrorMessage } from '@/utils/error-code/index'
import { sessionStorage } from '@/utils/storage'

const searchParams = ref({
  status: '',
  taskType: '',
  username: '',
  jobName: ''
})

const handleSearchParamsStatusChange = (status: TaskStatus) => {
  getPlans({ status })
}
const handleSearchParamsTaskTypeChange = (taskType: TaskType) => {
  getPlans({ task_type: taskType })
}
// const handleSearchParamsUsernameChange = (event: KeyboardEvent) => {
//   console.log(event)
// }
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  getPlans()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`, paginationProp)
  getPlans()
}

const store = useMyStore()
const workspaceId = sessionStorage.get(ELocalStorageKey.WorkspaceId)!

const paginationProp = reactive({
  pageSizeOptions: [10, 20, 50, 100],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 10,
  current: 1,
  total: 0
})

const columns = [
  {
    title: '计划/实际时间',
    dataIndex: 'duration',
    width: 200,
    slots: { customRender: 'duration' }
  },
  {
    title: '状态',
    key: 'status',
    width: 150,
    slots: { customRender: 'status' }
  },
  {
    title: '计划名称',
    dataIndex: 'job_name',
    width: 100
  },
  {
    title: '类型',
    dataIndex: 'taskType',
    width: 100,
    slots: { customRender: 'taskType' }
  },
  {
    title: '航线名称',
    dataIndex: 'file_name',
    width: 100
  },
  {
    title: '机场名称',
    dataIndex: 'dock_name',
    width: 100,
    ellipsis: true
  },
  {
    title: 'RTH相对于机场的高度（m）',
    dataIndex: 'rth_altitude',
    width: 120
  },
  {
    title: '航线飞行中失联',
    dataIndex: 'out_of_control_action',
    width: 120,
    slots: { customRender: 'lostAction' }
  },
  {
    title: '创建者',
    dataIndex: 'username',
    width: 120
  },
  {
    title: '媒体文件上传',
    key: 'media_upload',
    width: 160,
    slots: { customRender: 'media_upload' }
  },
  {
    title: '操作',
    width: 120,
    slots: { customRender: 'action' }
  }
]
type Pagination = TableState['pagination']

const plansData = reactive({
  data: [] as Task[]
})

const { formatTaskType, formatTaskTime, formatLostAction, formatTaskStatus, formatMediaTaskStatus } = useFormatTask()

// 设备任务执行进度更新
function onTaskProgressWs(data: TaskProgressInfo) {
  console.log('onTaskProgressWs----------------', data)
  const { bid, output } = data
  if (output) {
    const { status, progress } = output || {}
    const taskItem = plansData.data.find((task) => task.job_id === bid)
    if (!taskItem) return
    if (status) {
      taskItem.status = TaskProgressWsStatusMap[status]
      // 执行中，更新进度
      if (status === TaskProgressStatus.Sent || status === TaskProgressStatus.inProgress) {
        taskItem.progress = progress?.percent || 0
      } else if (
        [
          TaskProgressStatus.Rejected,
          TaskProgressStatus.Canceled,
          TaskProgressStatus.Timeout,
          TaskProgressStatus.Failed,
          TaskProgressStatus.OK
        ].includes(status)
      ) {
        getPlans()
      }
    }
  }
}

// 媒体上传进度更新
function onTaskMediaProgressWs(data: MediaStatusProgressInfo) {
  console.log('onTaskMediaProgressWs----------------', data)
  const { media_count: mediaCount, uploaded_count: uploadedCount, job_id: jobId } = data
  if (isNaN(mediaCount) || isNaN(uploadedCount) || !jobId) {
    return
  }
  const taskItem = plansData.data.find((task) => task.job_id === jobId)
  if (!taskItem) return
  if (mediaCount === uploadedCount) {
    taskItem.uploading = false
  } else {
    taskItem.uploading = true
  }
  taskItem.media_count = mediaCount
  taskItem.uploaded_count = uploadedCount
}

function onoTaskMediaHighestPriorityWS(data: TaskMediaHighestPriorityProgressInfo) {
  const { pre_job_id: preJobId, job_id: jobId } = data
  const preTaskItem = plansData.data.find((task) => task.job_id === preJobId)
  const taskItem = plansData.data.find((task) => task.job_id === jobId)
  if (preTaskItem) {
    preTaskItem.uploading = false
  }
  if (taskItem) {
    taskItem.uploading = true
  }
}

function getCodeMessage(code: number) {
  return getErrorMessage(code) + `（code: ${code}）`
}

useTaskWsEvent({
  onTaskProgressWs,
  onTaskMediaProgressWs,
  onoTaskMediaHighestPriorityWS
})

onMounted(() => {
  getPlans()
})

function getPlans(params: any = {}) {
  const newParams = { page: paginationProp.current, page_size: paginationProp.pageSize, ...params }
  getWaylineJobs(workspaceId, newParams).then((res) => {
    if (res.code !== 1) {
      return
    }
    plansData.data = res.data.list
    paginationProp.total = res.data.pagination.total
    paginationProp.current = res.data.pagination.page
  })
}

// 删除任务
async function onDeleteTask(jobId: string) {
  const { code } = await deleteTask(workspaceId, {
    job_id: jobId
  })
  if (code === 1) {
    message.success('Deleted successfully')
    getPlans()
  }
}

// 挂起任务
async function onSuspendTask(jobId: string) {
  const { code } = await updateTaskStatus(workspaceId, {
    job_id: jobId,
    status: UpdateTaskStatus.Suspend
  })
  if (code === 1) {
    message.success('Suspended successfully')
    getPlans()
  }
}

// 解除挂起任务
async function onResumeTask(jobId: string) {
  const { code } = await updateTaskStatus(workspaceId, {
    job_id: jobId,
    status: UpdateTaskStatus.Resume
  })
  if (code === 1) {
    message.success('Resumed successfully')
    getPlans()
  }
}

// 立即上传媒体
async function onUploadMediaFileNow(jobId: string) {
  const { code } = await uploadMediaFileNow(workspaceId, jobId)
  if (code === 1) {
    message.success('Upload Media File successfully')
    getPlans()
  }
}
</script>

<style lang="scss" scoped>
.plan-panel-wrapper {
  width: 100%;
  background: rgba(3, 5, 7, 0.9);
  padding: 16px;
  height: 100%;
}

.task-panel {
  background: rgba(8, 16, 26, 0.8); /* 调整背景颜色，并增加透明度 */
  border: 1px solid #333; /* 添加边框 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
  .width-common {
    width: vw(168);
    background-color: rgba(48, 48, 48, 0.3);
    border: 1px solid #dbdbdb;
    border-radius: 4px;
  }
}
</style>
